import json
import datetime
import export
import os
from django.http import FileResponse
from django.shortcuts import render,redirect
from createdb import Game_userinfo,Session,number,register_info,Game_userinfo_record
from django.http import HttpResponse,JsonResponse,QueryDict
import logging

logger = logging.getLogger("mylogger")

def index(request):
    return render(request,'index.html')

def apis(request):
    if request.method == 'POST':
        data = request.body
        print("request.POST: ",request.POST)
        # result = json.dumps(request.POST)
        # print("result: ",result,type(result))

    return HttpResponse(data)

def info(request):
    session = Session()
    if request.method == 'POST':
        username = request.POST.get("username")
        email = request.POST.get("email")
        phone = request.POST.get("phone")
    query1 = session.query(Game_userinfo_record).filter(Game_userinfo_record.user_email==email)
    isNone = query1.first()
    if isNone!=None:
        user_info = "You have an appointment"
    else:
        userinfo = Game_userinfo_record(username=username,user_email=email,user_phone=phone,time=datetime.datetime.utcnow())
        session.add_all([userinfo])
        user_info = "Appointment successful"
        session.commit()
        session.close()
    return  render(request,'result.html',{'info':user_info})

def subscribe(request):
    session = Session()
    if request.method == 'POST':
        email = request.POST.get("email")
        phone = request.POST.get("phone")

    query1 = session.query(register_info).filter(register_info.user_email==email)
    isNone = query1.first()
    if isNone!=None:
        data = "error"
        user_info = "You have an appointment"
    else:
        data = "success"
        logger.info("email: {}".format(email))
        logger.info("phone: {}".format(phone))
        logger.info("time: {}".format(datetime.datetime.now()))
        userinfo = register_info(user_phone=phone,user_email=email,time=datetime.datetime.now())
        session.add_all([userinfo])
        user_info = "Appointment successful"
        session.commit()
        session.close()
    return HttpResponse(json.dumps({'info':user_info,'data':data}))

def get_subscribe(request):
    session = Session()
    query1 = session.query(register_info).all()
    result = []
    if request.method == 'GET':
        for obj in query1:
            data = {}
            data["index"] = obj.id
            data["user_email"] = obj.user_email
            data["user_phone"] = obj.user_phone
            data["time"] = obj.time
            result.append(data)
    return JsonResponse({"result":result})



def get_count(request):
    session = Session()
    print(request.POST)
    if request.method == 'GET':
        try:
            query = session.query(register_info)
            ll = query.all()
            query1 = session.query(number).filter(number.id==1)
            count = query1.first().count
            num = len(ll)
            result = (num + count) / 100000 * 100
            if result >= 100:
                result = 100
            data = "success"
            session.commit()
            session.close()
        except Exception as e:
            data = e
            result = 0

    return HttpResponse(json.dumps({'result':result,'data':data}))

def updat_table():
    session = Session()
    query = session.query(number).filter(number.id==1)
    num = query.first()
    num.count +=  1
    print("已更新count", num.count)
    session.commit()
    session.close()


def download(request):
    file_name = "userinfo.xls"
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    file_path = os.path.join(base_dir,file_name)
    print("base_dir: ",base_dir)
    print("file_path: ",file_path)

    export.export_excel("userinfo")

    if not os.path.isfile(file_path):
        return HttpResponse("文件不存在！")

    file = open(file_path,'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)

    return response
